package com.example.spring_mybatis.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.schema.Column;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * 多租户配置文件(有问题)
 */
//@Configuration
public class MyBatisPlusTenantConfig {
    // 定义当前项目中多租户标识字段
    private static final String SYSTEM_TENANT_ID = "tenant_id";
    private static final List<String> IGNORE_TENANT_TABLES = new ArrayList<>();

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        System.out.println("--------------开始多租户拦截------------------");
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor());
        return interceptor;
    }

    private TenantLineInnerInterceptor tenantLineInnerInterceptor() {
        TenantLineHandler tenantLineHandler = new TenantLineHandler() {
            // 设置租户id
            @Override
            public Expression getTenantId() {
                // TODO 临时写死
                String tenantId = "123456";
                if (tenantId.isEmpty()) {
                    throw new RuntimeException(("租户id不能为空"));
                }
                return new StringValue(tenantId);
            }

            // 设置租户id所对应的表字段
            @Override
            public String getTenantIdColumn() {
                // 获取租户字段名,默认字段名叫: tenant_id
                return SYSTEM_TENANT_ID;
            }

            // 表过滤器
            @Override
            public boolean ignoreTable(String tableName) {
                return IGNORE_TENANT_TABLES.stream().anyMatch((e) -> e.equalsIgnoreCase(tableName));
            }

            // 忽略插入租户字段逻辑(如果插入数据事没有设置租户ID的值,那么这里会插入getTenantId方法返回的值)
            @Override
            public boolean ignoreInsert(List<Column> columns, String tenantIdColumn) {
                return TenantLineHandler.super.ignoreInsert(columns, tenantIdColumn);
            }
        };
        return new TenantLineInnerInterceptor(tenantLineHandler);
    }
}





























